package com.example.deliveryapp;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import me.jessyan.autosize.internal.CustomAdapt;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SignUpActivity extends AppCompatActivity implements CustomAdapt {

    private EditText phoneEditText;
    private EditText passwordEditText;
    private EditText confirmPasswordEditText;
    private Button registerButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);

        // 设置内容视图为您的布局XML
        setContentView(R.layout.sign_up);

        //返回上一Activity
        ImageButton button_back_on_sign_up = findViewById(R.id.button_back_on_sign_up);
        button_back_on_sign_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish(); // 结束当前Activity，返回上一Activity
            }
        });

        //初始化输入框和按钮
        EditText phoneEditText = findViewById(R.id.phone_on_sign_up);
        EditText passwordEditText = findViewById(R.id.password_on_sign_up);
        EditText confirmPasswordEditText = findViewById(R.id.edit_confirem_password_on_sign_up);
        Button registerButton = findViewById(R.id.create_account);

        //注册按钮点击事件
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取用户输入的数据
                String phone = phoneEditText.getText().toString().trim();
                String password = passwordEditText.getText().toString().trim();
                String confirmPassword = confirmPasswordEditText.getText().toString().trim();

                // 检查两次输入的密码是否一致
                if (!password.equals(confirmPassword)) {
                    Toast.makeText(SignUpActivity.this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 发送注册请求
                try {
                    sendRegisterRequest(phone, password);
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }


            }
        });




        //点击图标实现隐藏密码或显示密码功能(新建密码）
        ImageView eye_on_password_on_sign_up = findViewById(R.id.eye_on_password_on_sign_up);
        eye_on_password_on_sign_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int currentInputType = passwordEditText.getInputType();

                if ((currentInputType & InputType.TYPE_CLASS_TEXT) != 0 &&
                        (currentInputType & InputType.TYPE_TEXT_VARIATION_PASSWORD) != 0) {
                    // 密码当前是隐藏的
                    passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
                    eye_on_password_on_sign_up.setImageResource(R.drawable.eye_open); // 显示睁眼图标
                } else {
                    // 密码当前是显示的
                    passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    eye_on_password_on_sign_up.setImageResource(R.drawable.eye_close); // 显示闭眼图标
                }
            passwordEditText.setSelection(passwordEditText.getText().length()); // 将光标移动到文本末尾
            }
        });

        //点击图标实现隐藏密码或显示密码功能(重复密码）
        ImageView eye_on_confirem_password_on_sign_up = findViewById(R.id.eye_on_confirem_password_on_sign_up);
        eye_on_confirem_password_on_sign_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int currentInputType = confirmPasswordEditText.getInputType();

                if ((currentInputType & InputType.TYPE_CLASS_TEXT) != 0 &&
                        (currentInputType & InputType.TYPE_TEXT_VARIATION_PASSWORD) != 0) {
                    // 密码当前是隐藏的
                    confirmPasswordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
                    eye_on_confirem_password_on_sign_up.setImageResource(R.drawable.eye_open); // 显示睁眼图标
                } else {
                    // 密码当前是显示的
                    confirmPasswordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    eye_on_confirem_password_on_sign_up.setImageResource(R.drawable.eye_close); // 显示闭眼图标
                }
            confirmPasswordEditText.setSelection(confirmPasswordEditText.getText().length()); // 将光标移动到文本末尾
            }
        });



    }
    private void sendRegisterRequest(String phone, String password) throws JSONException {

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("phone", phone);
        jsonBody.put("password", password);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonBody.toString());

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://107.172.88.177:86/v1/register") // 替换为实际的注册接口 URL
                .post(requestBody)
                .addHeader("Content-Type", "application/json; charset=utf-8") // 根据需要添加请求头
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(() -> {
                    Toast.makeText(SignUpActivity.this, "注册失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String responseData = response.body().string();
                    runOnUiThread(() -> {
                        Toast.makeText(SignUpActivity.this, "注册成功: " + responseData, Toast.LENGTH_LONG).show();
                        //注册成功后，跳转至登录页
                        Intent intent = new Intent(SignUpActivity.this,SignInActivity.class);
                        startActivity(intent);

                    });
                } else {
                    runOnUiThread(() -> {
                        Toast.makeText(SignUpActivity.this, "注册失败，状态码：" + response.code(), Toast.LENGTH_LONG).show();
                    });
                }
            }
        });
    }
    @Override
    public boolean isBaseOnWidth() {
        return true;
    }

    @Override
    public float getSizeInDp() {
        return 390;
    }

}
